import { container } from "tsyringe"
import { HTTP_GET, HTTP_POST } from "../tokens/http"
import axios from 'axios'
import { CLOUD_HOST, CLOUD_PORT, DEVICE_NAME, DEVICE_UUID, TOKEN, getCloudHost, getCloudPort, getToken } from "../tokens/const"
import { configTokenFactory } from "../utils/configTokenFactory"
import { CONFIG } from "../tokens/core"
import { Config } from "./config"

export function bootstrap() {
    container.registerSingleton(CONFIG, Config);
    container.register(HTTP_GET, {
        useValue: (url, params) => {
            const host = getCloudHost()
            const port = getCloudPort()
            const token = getToken()
            return axios.get(`http://${host}:${port}/autojs/core/autox/${url}`, {
                params: params,
                headers: {
                    Authorization: `web ${token}`
                },
            }).then(res => {
                const { success, message, data } = res.data;
                if (success) {
                    return data;
                } else {
                    throw new Error(message)
                }
            })
        }
    })
    container.register(HTTP_POST, {
        useValue: (path, body) => {
            const host = getCloudHost()
            const port = getCloudPort()
            const token = getToken()
            const url = `http://${host}:${port}/autojs/core/autox/${path}`;
            console.log(`post ${url}`, body)
            return axios.post(url, body, {
                headers: {
                    Authorization: `web ${token}`
                },
            }).then(res => {
                const { success, message, data } = res.data;
                if (success) {
                    return data;
                } else {
                    throw new Error(message)
                }
            })
        }
    })
    configTokenFactory(TOKEN)
    configTokenFactory(DEVICE_NAME)
    configTokenFactory(DEVICE_UUID)
    container.register(CLOUD_HOST, {
        useValue: `60.204.248.43`
    });
    container.register(CLOUD_PORT, {
        useValue: 3102
    });
}
